package controllers

import (
	"github.com/gin-gonic/gin"
	"signature-service/global"
	"signature-service/repositories"
	"signature-service/services"
	"strconv"
	"strings"
	"sync"
)

type SignController struct {
	mu sync.Mutex // 添加一个互斥锁
}

func NewSignController() *SignController {
	return &SignController{}
}

// GenerateAddress 生成地址
func (s *SignController) GenerateAddress(c *gin.Context) {

	flag := c.DefaultQuery("flag", "EVM")
	service := services.NewSignService()
	address, id, err := service.GenerateAddress(strings.ToUpper(flag))
	if err != nil {
		c.JSON(200, global.Fail(err.Error()))
		return
	}
	c.JSON(200, global.Success(&map[string]any{
		"address": address,
		"id":      id,
	}))
}

// GetSign 获取签名
func (s *SignController) GetSign(c *gin.Context) {
	id := c.MustGet("id").(string)
	tokenAddress := c.MustGet("tokenAddress").(string)
	value := c.MustGet("value").(string)
	to := c.MustGet("to").(string)
	rpcUrl := c.MustGet("rpcUrl").(string)

	service := services.NewSignService()
	var privateKeys repositories.PrivateKeys
	privateKeys.ID = id
	err := privateKeys.FindOne()
	if err != nil {
		c.JSON(200, global.Fail(err.Error()))
		return
	}

	if privateKeys.Type == "EVM" {
		sign, err := service.GetEvmSign(privateKeys, to, tokenAddress, value, rpcUrl)
		if err != nil {
			c.JSON(200, global.Fail(err.Error()))
			return
		}
		c.JSON(200, global.Success(sign))
		return

	} else {
		// TRX
		sign, err := service.GetTrxSign(privateKeys, to, tokenAddress, value, rpcUrl)
		if err != nil {
			c.JSON(200, global.Fail(err.Error()))
			return
		}
		c.JSON(200, global.Success(sign))
		return
	}
}

// GetTokenForTokenSign 获取UU兑换签名
func (s *SignController) GetTokenForTokenSign(c *gin.Context) {
	id := c.DefaultQuery("id", "")
	rpcUrl := c.DefaultQuery("rpcUrl", "")
	to := c.DefaultQuery("to", "")
	tokenAddress := c.DefaultQuery("tokenAddress", "")
	value := c.DefaultQuery("value", "")
	flag := c.DefaultQuery("flag", "")
	if id == "" || rpcUrl == "" || to == "" || tokenAddress == "" || value == "" || flag == "" {
		c.JSON(200, global.Fail("参数错误"))
		return
	}

	service := services.NewSignService()
	// mainCoinType 转为 int64
	flagInt64, _ := strconv.ParseInt(flag, 10, 64)
	sign, err := service.GetTokenForTokenSign(id, rpcUrl, to, tokenAddress, value, flagInt64)
	if err != nil {
		c.JSON(200, global.Fail(err.Error()))
		return
	}
	c.JSON(200, global.Success(sign))
}

// UpdateDecode 更新解码
func (s *SignController) UpdateDecode(c *gin.Context) {
	s.mu.Lock()
	defer s.mu.Unlock()

	service := services.NewSignService()
	err := service.UpdateDecode()
	if err != nil {
		c.JSON(200, global.Fail(err.Error()))
		return
	}
	c.JSON(200, global.Success(nil))
}
